package com.falcon.service.impl;

import com.falcon.scanner.IControllerScanner;
import com.falcon.service.IControllerMetaService;
import com.falcon.domain.req.ControllerQuery;
import com.falcon.domain.vo.ControllerMeta;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zongf
 * @date 2024-02-19
 **/
@Slf4j
@Service
public class ControllerMetaService implements IControllerMetaService {

    @Autowired
    private IControllerScanner controllerScanner;

    @Override
    public List<ControllerMeta> getBaseControllers(ControllerQuery request) {

        List<ControllerMeta> controllerMetas = this.controllerScanner.doScan(false, false, false);

        // 根据查询条件过滤
        List<ControllerMeta> results = controllerMetas.stream()
                .filter(vo -> {
                    boolean isMatch = true;
                    if (StringUtils.hasText(request.getModuleName())) {
                        isMatch &= vo.getModuleName().equals(request.getModuleName());
                    }
                    if (StringUtils.hasText(request.getSimpleName())) {
                        isMatch &= vo.getSimpleName().toUpperCase().startsWith(request.getSimpleName().toUpperCase());
                    }
                    if (StringUtils.hasText(request.getDescription())) {
                        isMatch &= vo.getDescription().toUpperCase().contains(request.getDescription().toUpperCase());
                    }
                    return isMatch;
                    })
                .sorted(Comparator.comparing(ControllerMeta::getModuleName))
                .collect(Collectors.toList());

        return results;
    }
}
